package com.zxg.zbc.web.common.module;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.requestcontext.buffered.BufferedRequestContext;
import com.alibaba.citrus.service.requestcontext.parser.ParameterParser;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.util.io.ByteArrayInputStream;
import com.zxg.util.WebUtil;
import com.zxg.zbc.biz.exception.ManagerException;
import com.zxg.zbc.biz.manager.UserManager;
import com.zxg.zbc.biz.util.ApiConfigs;
import com.zxg.zbc.biz.util.ElemeUtil;
import com.zxg.zbc.dal.dataobject.EUserShop;
import com.zxg.zbc.dal.dataobject.User;
import com.zxg.zbc.dal.query.BasePagerQuery;
import com.zxg.zbc.domain.UUIIResult;
import com.zxg.zbc.web.common.config.SessionConfig;

import eleme.openapi.sdk.api.entity.user.OUser;
import eleme.openapi.sdk.api.exception.ServiceException;
import eleme.openapi.sdk.api.service.UserService;
import eleme.openapi.sdk.oauth.response.Token;

public abstract class BaseUserModule {
public static Logger log                     = LoggerFactory.getLogger(BaseUserModule.class);

  @Autowired
  protected HttpSession      session;
  @Autowired
  private HttpServletRequest request;
  

  protected static Logger    LOG = LoggerFactory.getLogger(BaseUserModule.class);

  @Autowired
  protected UserManager userManager;
  public void execute(Context context, ParameterParser params, Navigator nav) {
    Boolean logout = params.getBoolean("logout", false);
    if (logout) {
      permission(null, null);
    }
    if (!skipPermission()) {
      User user = checkPermisionAndRedi(params, nav, context);
      if (user == null) {
        return;
      }
      context.put("isAdmin", this.isAdmin() ? 1 : 0);
      context.put("currentUser", user);

      doExecute(context, params, nav, user);

    } else {
      User user = checkPermision(params);
      context.put("isAdmin", this.isAdmin() ? 1 : 0);
      context.put("currentUser", user);
      doExecute(context, params, nav, user);
    }

  }

  protected User checkPermisionAndRedi(ParameterParser params, Navigator nav, Context context) {
	  User u = null;
		u = checkPermision(params);
		
		if(u == null ){
			u = oAuthedPage(params,context,nav);
			return u;
		}else{
			processAfterCheckPermission(context,u);
		}
		return u;
  }
  private void processAfterCheckPermission(Context context, User u) {
		context.put("user", u);
	}


  private User oAuthedPage(ParameterParser params, Context context, Navigator nav) {
  	
  		String code = params.getString("code");
  		//String state = params.getString("state"); TODO 以后判定来源
  		if(code == null){
  			redirectLogin(nav);
  			return null;
  		}
  			
  		User user = null;
  		
  		//处理饿了么授权
  		Token token = ElemeUtil.getTokenByCode(code);
  		if(token == null)
  		{
  			//TODO 授权错误
  			return null;
  		}
  		UserService userService = new UserService(ElemeUtil.config, token);
        try {
			   OUser ouser = userService.getUser();
		        
			   user = userManager.generateElemeLogin(ouser);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ManagerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
     
//      
//      try {
//          user = userManager.insertOrUpdateAfterLogin(user);
//      } catch (ManagerException e) {
//          log.error(e.getMessage(), e);
//      }
      if (user != null) {
          context.put("user", user);
          //session.setAttribute(SessionConfig.SESSION_USER, user);
          // add UserLoginSign
         
          permission(null, user);

          //doAfterLogin(user);

      }
      return user;
  }

  private void redirectLogin(Navigator nav) {
	 //TODO 以后需要根据url 判定走哪个登录
	String url = ElemeUtil.getAuthUrl("login", null);
	nav.redirectToLocation(url);
}

protected User checkPermision(ParameterParser params) {
    Object o = session.getAttribute(SessionConfig.SESSION_USER);
    if (o != null && o instanceof User) {
      User user = (User) o;
      return user;
    }
    return null;
  }

  public abstract void doExecute(Context context, ParameterParser params, Navigator nav, User loginUser);

  protected void convertSuccessJson(Object o, Context context) {
    try {
      context.put("result", new UUIIResult(true, o, "success"));
    } catch (Error e) {
      LOG.error("errorrrrrrr", e);
      context.put("result", new UUIIResult(true, o, "success"));

    } catch (Exception ee) {
      LOG.error("err", ee);
      context.put("result", new UUIIResult(true, o, "success"));
    }
  }

  protected void convertSuccessJson(BasePagerQuery query, Object o, Context context) {
    try {
      UUIIResult res = new UUIIResult(true, o, "success");
      res.setCount(query.getCount());
      res.setCurPage(query.getCurPage());
      res.setPageCount(query.getPageCount());

      context.put("result", res);
    } catch (Error e) {
      LOG.error("errorrrrrrr", e);
      context.put("result", new UUIIResult(true, null, "success"));

    } catch (Exception ee) {
      LOG.error("err", ee);
      context.put("result", new UUIIResult(true, null, "success"));
    }
  }

  protected void convertJson(Object o, Context context) {
    context.put("result", o);
  }

  protected void convertFailureJson(String message, Context context) {
    context.put("result", new UUIIResult(false, null, message));
  }

  protected boolean skipPermission() {
    return false;
  }

  protected void convertFailureJson(String message, Object o, Context context) {
    context.put("result", new UUIIResult(false, o, message));
  }

  protected void convertFailureJson(int code, String message, Context context) {
    context.put("result", new UUIIResult(false, code, message));
  }

  protected void convertSuccessJson(int code, String message, Context context) {
    context.put("result", new UUIIResult(true, code, message));
  }

  protected void permission(String sign, User u) {
    session.setAttribute(SessionConfig.SESSION_USER, u);
    if (u == null) {
      session.removeAttribute(SessionConfig.SESSION_ADMIN);
    }
    if (u != null) {
      if (u.getStatus() != null && ((u.getStatus().intValue() & ApiConfigs.RoleType.ADMIN) == ApiConfigs.RoleType.ADMIN)) {
        session.setAttribute(SessionConfig.SESSION_ADMIN, SessionConfig.SESSION_ADMIN);
      }
    }
  }
  	protected void permissionShop(EUserShop shop) {
	    session.setAttribute(SessionConfig.SESSION_ESHOP, shop);
	    
	  }
  public boolean isAdmin() {
    if (session.getAttribute(SessionConfig.SESSION_ADMIN) != null
        && SessionConfig.SESSION_ADMIN.equalsIgnoreCase(session.getAttribute(SessionConfig.SESSION_ADMIN).toString())) {
      return true;
    }
    return false;
  }



  protected boolean needCheckAdmin() {
    return false;
  }

  protected boolean isStoreBinded(User loginUser) {
   

    return false;
  }

  /**
   * 
   * 导出CSV文件报表
   * 
   * @param filename
   *          下载文件名
   * @param content
   *          下载内容字节数组
   * @throws Exception
   */
  public void exportCSVReport(String filename, byte[] content, BufferedRequestContext buffered, HttpServletResponse response) throws Exception {
    if (content == null) {
      throw new Exception("export content is null.");
    }
    if (StringUtils.isEmpty(filename)) {
      filename = "export";
    }
    filename += "_" + System.currentTimeMillis() + ".csv";

    buffered.setBuffering(false);
    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    OutputStream out = response.getOutputStream();
    response.setCharacterEncoding("GBK");
    BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));
    BufferedOutputStream bos = new BufferedOutputStream(out);
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = bis.read(buffer)) != -1) {
      bos.write(buffer, 0, length);
    }
    if (bis != null)
      bis.close();
    if (bos != null)
      bos.close();
  }

  protected void refreshUser(User user, Context context) {
    
  }

  protected User getUserFromSession() {
    User user = (User) session.getAttribute(SessionConfig.SESSION_USER);
    return user;
  }

  protected boolean checkCaptcha(String validCode) {

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("api_key", ApiConfigs.LUOSIMAO_API_KEY));
    params.add(new NameValuePair("response", validCode));
    String result = WebUtil.post(ApiConfigs.LUOSIMAO_API_URL, params);

    if (StringUtils.isNotEmpty(result)) {

      JSONObject json = JSONObject.fromObject(result);
      if (json != null) {
        String succeed = (String) json.get("res");
        if (StringUtils.equalsIgnoreCase("success", succeed)) {
          return true;
        }
      }

    }
    return false;
  }

}
